package com.purong.purong.util;

import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

/**
 * Created by zengwenjie on 2017/12/14.
 */
public class NumDecTextWatch implements TextWatcher {
    private EditText ed;
    public  NumDecTextWatch(EditText ed){
        this.ed=ed;
    }
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (s.toString().contains(".")) {
            if (s.toString().startsWith(".")) {
                ed.setText(s.toString().replaceFirst(".",""));
            }else if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                s = s.toString().subSequence(0,
                        s.toString().indexOf(".") + 3);
                ed.setText(s);
                ed.setSelection(ed.getText().toString().trim().length());
            }
        }

        if (s.toString().startsWith("0")
                && s.toString().trim().length() > 1) {
            if (!s.toString().substring(1, 2).equals(".")) {
                ed.setText(s.toString().replaceFirst("0",""));
                ed.setSelection(ed.getText().toString().trim().length());
            }
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }
}
